package com.dongdongshop.mq;

import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.service.TbOrderService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import java.util.Objects;


@RocketMQTransactionListener
public class OrderMqListner implements RocketMQLocalTransactionListener {
    @DubboReference(check = false)
    private TbOrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 执行本地事务的方法
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        String id = String.valueOf(message.getHeaders().getId());
        try {
            TbOrder order = (TbOrder) o;
            orderService.updateStatusByOrderNumAndItemOrder(order.getOrderNum(),order.getTradeNum());
            redisTemplate.boundValueOps(id).set("1");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            redisTemplate.boundValueOps(id).set("0");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String messageId = String.valueOf(message.getHeaders().getId());
        String o = (String) redisTemplate.boundValueOps(messageId).get();
        if (Objects.equals(o,"1")){
            return RocketMQLocalTransactionState.COMMIT;//提交
        }else if(Objects.equals(o,"0")){
            return RocketMQLocalTransactionState.ROLLBACK;//回滚
        }else {
            return RocketMQLocalTransactionState.UNKNOWN;//未知的意思
        }
    }
}
